# -*- coding: UTF-8 -*-
import os
import re
import time
import traceback
import requests
from db_interface import db_interface
from srf_log import logger
import requests
from public_func.user_agent import User_Agent
import json, random
import datetime


def ids_stock_name_data():
    sql = "select ids_name, ids, stock, name from ids_stock_list"
    query = db_interface.stock_base.select(sql)
    data = {}
    for item in query:
        ids_name, ids, stock, name = item
        if ids_name not in data:
            data[ids_name] = []
        data[ids_name].append(
            (ids, stock, name)
        )
    return data

def cal_ids_mkv_pe(ids='银行', data=[], code='BK0475'):
    # data = [('BK0475', '601860', '紫金银行'), ('BK0475', '002839', '张家港行'), ('BK0475', '600928', '西安银行'), ('BK0475', '600919', '江苏银行'), ('BK0475', '603323', '苏农银行'), ('BK0475', '002948', '青岛银行'), ('BK0475', '601939', '建设银行'), ('BK0475', '601288', '农业银行'), ('BK0475', '002966', '苏州银行'), ('BK0475', '002958', '青农商行'), ('BK0475', '601997', 'XD贵阳银'), ('BK0475', '601998', '中信银行'), ('BK0475', '601916', '浙商银行'), ('BK0475', '601818', '光大银行'), ('BK0475', '600016', '民生银行'), ('BK0475', '600015', '华夏银行'), ('BK0475', '002936', '郑州银行'), ('BK0475', '002807', '江阴银行'), ('BK0475', '601838', '成都银行'), ('BK0475', '601169', '北京银行'), ('BK0475', '601077', '渝农商行'), ('BK0475', '601658', '邮储银行'), ('BK0475', '601988', '中国银行'), ('BK0475', '601577', '长沙银行'), ('BK0475', '601328', '交通银行'), ('BK0475', '600908', '无锡银行'), ('BK0475', '601128', '常熟银行'), ('BK0475', '600000', '浦发银行'), ('BK0475', '601166', '兴业银行'), ('BK0475', '601229', '上海银行'), ('BK0475', '601398', '工商银行'), ('BK0475', '601009', '南京银行'), ('BK0475', '600036', '招商银行'), ('BK0475', '000001', '平安银行'), ('BK0475', '002142', '宁波银行'), ('BK0475', '600926', '杭州银行')]
    stock_sh = [x[1] for x in data if x[1].startswith('6')]
    stock_sz = [x[1] for x in data if not x[1].startswith('6')]
    if len(stock_sz) > 1 and len(stock_sh) > 1:
        sql = "select stock, date, pe_ttm, mkv from stock_pe_sh where stock in {} union " \
              "select stock, date, pe_ttm, mkv from stock_pe_sz where stock in {} order by date asc". \
            format(
            tuple(stock_sh), tuple(stock_sz)
        )
    else:
        if len(stock_sh) == 1:
            sql = "select stock, date, pe_ttm, mkv from stock_pe_sh where stock  = '{}' union " \
                  "select stock, date, pe_ttm, mkv from stock_pe_sz where stock in {} order by date asc". \
                format(
                    stock_sh[0], tuple(stock_sz)
            )
        else:
            sql = "select stock, date, pe_ttm, mkv from stock_pe_sh where stock in {} union " \
                  "select stock, date, pe_ttm, mkv from stock_pe_sz where stock = '{}' order by date asc". \
                format(
                tuple(stock_sh), stock_sz[0]
            )
    data = {}
    query = db_interface.stock_base.select(sql)
    for item in query:
        stock, date, pe_ttm, mkv = item
        date = date.strftime('%Y-%m-%d')
        if date not in data:
            data[date] = []
        data[date].append(
            (stock, pe_ttm, mkv)
        )
    for k, v in data.items():
        mkv_all = [x[2] for x in v]
        pe_all = [x[1]*x[2] for x in v]
        mkv_sum = sum(mkv_all)
        avg_pe = sum(pe_all)/mkv_sum
        data_dict = {
            'name': ids,
            'code': code if code else '',
            'date': k,
            'mkv': mkv_sum,
            'pe': avg_pe
        }

        db_interface.stock_base.insert_dict('dongcai_ids_pe', data_dict)
        print('insert into dongcai_ids_pe: %s' % data_dict)
        # exit(-1)


def update_ids_pe_mkv():
    has_ids = []
    sql = "select distinct name from dongcai_ids_pe"
    query = db_interface.stock_base.select(sql)
    for item in query:
        has_ids.append(item[0])
    data = ids_stock_name_data()
    for k, v in data.items():
        code = v[0][0]
        if k in has_ids:
            continue
        print(k)
        cal_ids_mkv_pe(ids=k, data=v, code=code)






if __name__ == "__main__":
    update_ids_pe_mkv()